'''
pdf_convert_png.py
解析pdf为png图片
'''
 
import sys, fitz
import os
import datetime
import re;
from setting import pdf_path,image_path;
 
png_count = 0;
 
 
def pdf_convert_png(pdf_path,pdf_file_name, imagePath,count):
    global png_count;
    complete_pdf_path = pdf_path+"/"+pdf_file_name;
    #print("完整路径:"+complete_pdf_path);
    pdfDoc = fitz.open(complete_pdf_path)
    for pg in range(pdfDoc.pageCount):
        page = pdfDoc[pg]
        rotate = int(0)
        # 每个尺寸的缩放系数为1.3，这将为我们生成分辨率提高2.6的图像。
        # 此处若是不做设置，默认图片大小为：792X612, dpi=96
        zoom_x = 2 #(1.33333333-->1056x816)   (2-->1584x1224)
        zoom_y = 2
        mat = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
        pix = page.getPixmap(matrix=mat, alpha=False)
        
        if not os.path.exists(imagePath):#判断存放图片的文件夹是否存在
            os.makedirs(imagePath) # 若图片文件夹不存在就创建
        
        pix.writePNG(imagePath+'/'+str(count)+'-images_%s.png' % pg)#将图片写入指定的文件夹内
        png_count = png_count + 1;
    print("[.]解析成png图片数:",png_count);
 
def reload_fileNames(pdfPath,types):
    pdf_files = []; #存储将要转换pdf的名称
    for filename in os.listdir(pdfPath):
        if filename.endswith(types):
            pdf_files.append(filename);
    print("装载文件个数:{} 文件类型:{}".format(len(pdf_files),types));
    return pdf_files;
# if __name__ == "__main__":
#     pdf_files = reload_fileNames(pdfPath,'pdf');
#     #对文件名称排序
#     pdf_files = sorted(pdf_files,key = lambda i:int(re.match(r'(\d+)',i).group()))
#     print(pdf_files);
#     count = 1;
#     for p in pdf_files:
#         print("当前转换pdf:{}".format(p));
#         pdf_convert_png(pdf_path,p, image_path,count)
#         count = count + 1; #计算pdf数量